#!/usr/bin/env ruby

# Copyright (c) 2017 Minqi Pan <pmq2001@gmail.com>
#                    Yuwei Ba <xiaobayuwei@gmail.com>
#                    Alessandro Agosto <agosto.alessandro@gmail.com>
# 
# This file is part of Node.js Compiler, distributed under the MIT License
# For full terms see the included LICENSE file

STDERR.puts "Testing coffeescript"

require 'shellwords'
require 'fileutils'
require 'tmpdir'

def escape(arg)
  if Gem.win_platform?
    if arg.include?('"')
      raise NotImplementedError
    end
    %Q{"#{arg}"}
  else
    Shellwords.escape(arg)
  end
end

if ENV['NODEC_TESTS_TMPDIR'] && ENV['NODEC_TESTS_TMPDIR'].length > 0
  STDERR.puts "Using ENV['NODEC_TESTS_TMPDIR'] #{ENV['NODEC_TESTS_TMPDIR']}"
else
  raise "Please set ENV['NODEC_TESTS_TMPDIR']"
end
tmpdir = ENV['NODEC_TESTS_TMPDIR']

unless Dir.exist?('coffeescript')
  puts `git clone --depth 1 https://github.com/jashkenas/coffeescript.git`
  raise 'git failed' unless $?.success?
end
Dir.chdir('coffeescript')

outpath = File.expand_path((Gem.win_platform? ? 'a.exe' : 'a.out'), Dir.pwd)
FileUtils.rm_f(outpath)

tmpdir_node = File.join(tmpdir, "node-#{`ruby ../bin/nodec --node-version`.strip}-#{`ruby ../bin/nodec --version`.strip}")

pid = spawn("ruby ../bin/nodec --tmpdir=#{escape tmpdir} bin/coffee")
pid, status = Process.wait2(pid)
raise "Failed running nodec for coffeescript" unless status.success?

raise unless File.exist?(outpath)
raise unless File.size(outpath) >= 10_000_000

if Gem.win_platform?
  outpath = %Q{"#{outpath}"}
else
  File.chmod(0777, outpath)
  outpath = escape(outpath)
end

# PART 1
raise unless `#{outpath} --help`.include?(%q{If called without options, `coffee` will run your script.})
raise unless $?.success?
raise unless 64 == `#{outpath} --eval "console.log(((x) -> x * x)(8))"`.to_i
raise unless $?.success?
STDERR.puts "coffeescript Passed."

# PART 2
STDERR.puts "Testing coffeescript with node's official test cases"
Dir.chdir(tmpdir_node)
ENV['ENCLOSE_IO_USE_ORIGINAL_NODE'] = '1'
if Gem.win_platform?
  pid = spawn("call vcbuild.bat release nosign noprojgen nobuild test-simple ignore-flaky ")
  pid, status = Process.wait2(pid)
  raise "Failed running call vcbuild.bat release nosign noprojgen nobuild test-simple ignore-flaky" unless status.success?
else
  ENV['FLAKY_TESTS'] = 'dontcare'
  pid = spawn("make test-simple")
  pid, status = Process.wait2(pid)
  raise "Failed running make test-simple" unless status.success?
end
STDERR.puts "coffeescript with node's official test cases Passed"
